import adModel from "../../../main/view/adView/adModel";
import { UIMgr } from "../../manager/viewMgr";
import { ZYEventMgr } from "../../manager/YLEventMgr";
import { WXAPIMgr } from "../concrete/WXAPIManager";

/**
 * 
 * @author: xj.huang
 * @date: 2021/08/03 10:00:28
 */
export default class wxBanner {
    /**是否支持广告默认：true */
    protected _tencentApi: any = window['wx'];
    public isSupportBannerAd = true;
    /**广告最大请求树 */
    private _maxRequerNum: number = 3;
    /**广告对象池最大数 */
    private _bannerPoolMax: number = 5;
    /**广告对象池-用于缓存广告对象，就是在广告加载失败时从对象池拿出来用 */
    private _bannerPool: wx.BannerAd[] = [];
    /**当前广告索引 - 默认：0 */
    private _bannerIndex: number = 0
    /**广告时间 */
    private _loopBannerTime;
    /**是否已经初始化 */
    private isInit = false;
    /**当前微信小游戏是否在运行 用于 */
    private _isWxGameStop = true;
    /**广告视图界面 */
    private BannerNodeView: ZYSDK.BannerView;
    /**当前广告 */
    private currBanner: wx.BannerAd;
    /**当前广告显示状态 */
    private bannerShowing = false;
    /**当前广告拉取成功失败状态 */
    private isHasCurrBanner = false;
    private gameConfig: Game.Config
    constructor() {
        wxBanner._instance = this;
    }
    private static _instance: wxBanner;
    public static get instance(): wxBanner {
        if (!this._instance) {
            this._instance = new wxBanner();
        }
        return this._instance;
    }
    /**初始化微信广告 */
    public initWxBannerAd() {
        if (this.isInit) return
        console.log("载入广告")
        this.bannerShowing = true;
        this.gameConfig = adModel.gameConfig;
        this.isInit = true;
        this.loopBannerTime = this.gameConfig.adv_interval.force_wx;

        this.isWxGameStop = false;
        this.BannerNodeView = UIMgr.onGetRuntime(ViewRes.VIEW_BANNER);
        // this.onShowBanner()
        if (Laya.Browser.onWeiXin) this.onActivate()
        //根据后台配置刷新
        ZYEventMgr.on(ADEvent.SHOW_BANNER_AD, this, this.onShowBanner)
        ZYEventMgr.on(ADEvent.HIDE_BANNER_AD, this, this.onHideBanner)
        ZYEventMgr.on(GameEvent.ON_CHANGE_BANNER, this, this.onLoadeBanner)

    }
    private set loopBannerTime(val) {
        this._loopBannerTime = val ? val : adModel.gameConfig.adv_interval.force_wx
    }
    /** 监听 - 显示微信广告 */
    public onShowBanner(reSetTime?: number) {
        if(adModel.isFocreHiddeBanner) return;
        this.bannerShowing = true;
        console.warn("开启广告")
        if (this.currBanner) {
            this.showBanner(this.currBanner)
        } else if (this._bannerPool[0]) {
            this.showBanner(this._bannerPool[0])
        } else {
            this.onLoadeBanner()
        }
        reSetTime && this.onReSetTimer(true, reSetTime)
    }
    /**调用显示方法 */
    private showBanner(currBanner) {
        console.warn("this.bannerShowing", this.bannerShowing, currBanner)
        if (!this.bannerShowing || adModel.isFocreHiddeBanner) return;
        currBanner.show();
        this.setCellAdActive = false;
    }
    /**监听 - 关闭广告 */
    public onHideBanner(isOffAll = false) {
        this.bannerShowing = false;
        if (this.currBanner) {
            this.currBanner.hide();
            this.setCellAdActive = true;
        } else if (this._bannerPool[0]) {
            this._bannerPool[0].hide();
        } else {
            console.info("当前没有展示的广告哦!")
        }
        console.log("isOffAll", isOffAll)
        isOffAll && ZYEventMgr.emit(ADEvent.NOT_AD)
    }
    /**获取banner id */
    private get getBannerId() {
        if (!Laya.Browser.onWeiXin) return false;
        let banner = adModel.gameConfig.adv_unit_conf.banner;
        this._bannerIndex++;
        if (this._bannerIndex >= banner.length) {
            this._bannerIndex = 0;
        }
        if (!banner[this._bannerIndex]) {
            console.warn("无效广告>>>>参数解析：" + "bannerIndex:", this._bannerIndex, "banner:", banner)
            return false
        }
        return banner[this._bannerIndex];
    }
    /** 每隔20秒拉取广告 -后台配置 */
    private onUpdata() {
        if (adModel.stopBannerTimer) return;
        if (!this._isWxGameStop && this.bannerShowing) return;
        if ((this._loopBannerTime -= 0.1) <= 0) {
            this.onReSetTimer()
            this.onLoadeBanner()
        }
    }
    /**
     * 
     * @param isStop 是否重新计时
     * @param timer 停止多久不填则默认使用配置时间
     */
    public onReSetTimer(isStop: boolean = false, timer: number = adModel.gameConfig.adv_interval.force_wx) {
        if (isStop && this.currBanner || isStop && this._bannerPool[0]) {
            this.loopBannerTime = timer;
        } else {
            this.loopBannerTime = adModel.gameConfig.adv_interval.force_wx
        }
    }
    /**加载广告完成商家欧酷 */
    private async onLoadeBanner() {
        let banner = await WXAPIMgr.createBannerAd(this.getBannerId)
        if (banner) {
            this.onCreatBannerSuccess(banner)
        } else if (banner === undefined) {
            this.onCreatBannerError(banner)
        } else {
            console.log("<<<<<不在微信内>>>>>")
        }
    }
    /**创建banner错误 */
    private onCreatBannerError(banner) {
        if (this._maxRequerNum-- >= 0) {
            Laya.timer.once(3000, this, this.onLoadeBanner);
            console.warn(`第${this._maxRequerNum}加载失败，3秒之后重新拉取广告`)
            return;
        }
        if (this._bannerPool[0]) {
            console.warn(`使用上一次广告`)
            this.showBanner(this._bannerPool[0])
        } else {
            // 广告拉取失败，等待下一次轮回
            //code
            if (this.isHasCurrBanner) return;
        }
    }
    /**创建banner成功 */
    private onCreatBannerSuccess(banner) {
        // console.log("创建成功")
        this._maxRequerNum = 3;
        this.currBanner = banner;
        this.loopBannerTime = adModel.gameConfig.adv_interval.force_wx;
        this._bannerPool[0] && this._bannerPool[0].destroy();
        this._bannerPool[0] = this.currBanner;
        this.showBanner(banner)
    }

    public set isWxGameStop(val) {
        this._isWxGameStop = val
    }
    /**显示格子广告轮播图 */
    public set showCellBanner(v) {
        v ? this.BannerNodeView?.onShowCellBanner() : this.BannerNodeView?.onHideCellBanner();
        v && this.isHasCurrBanner && this.currBanner.hide()
    }


    /**销毁广告 */
    public onDestroy() {
        Laya.timer.clear(this, this.onUpdata)
        this.isWxGameStop = false;
        this.bannerShowing = false;
        this._bannerPool[0]?.hide()
        this.currBanner?.destroy();
    }
    /**激活广告-初始化调用 */
    private onActivate() {
        this.isWxGameStop = true;
        this.bannerShowing = true;
        this.onShowBanner()
        Laya.timer.clear(this, this.onUpdata)
        Laya.timer.loop(100, this, this.onUpdata)
    }
    /**设置格子广告激活状态 */
    private set setCellAdActive(v) {
        // if(adModel.isFocreHiddeBanner){
        v && ZYEventMgr.emit(ADEvent.SHOW_GIRID_AD)
        !v && ZYEventMgr.emit(ADEvent.HIDE_GIRID_AD)
        // }
        this.BannerNodeView?.onHideCellBanner();
        adModel.bannerShowType = !v;
    }
}
// export const wxBannerMgr = wxBanner.instance;


